//
//  PersonOrderListViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/11.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "CollectionListViewController.h"
#import "OrderModel.h"
#import "PersonOrderDetailViewController.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "GoodDetailViewController.h"
#import "OrderViewController.h"
#import "TransforController.h"
#import "SportsDetailViewController.h"
#import "StrategyDetailViewController.h"

@interface CollectionListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,assign) int currentIndex;


@property(nonatomic, strong)NSMutableArray *array_data;

@end

@implementation CollectionListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self initView];
    self.currentIndex = -1;
    [self setEnableRefresh:YES];
    [self setEnableLoadMore:YES];
//    [self getCommentList];
//    [self.view setFrame:CGRectMake(0, 65, 320, 568)];
    
    UIBarButtonItem *backItem=self.navigationItem.backBarButtonItem;
    backItem.title=@"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)initView{
//    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0];
//    [self.view addSubview:view_navigationBar];
//    self.navigationItem.title = @"我的收藏";
    self.view_table = [[PullTableView alloc]initWithFrame:CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.size.width, self.view.bounds.size.height - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR - HEIGHT_BOTTOM_BAR + 5) style:UITableViewStylePlain];
    self.view_table.dataSource = self;
    self.view_table.delegate = self;
    self.view_table.pullDelegate = self;
    self.view_table.tableFooterView = [[UIView alloc]init];
    self.array_data = [[NSMutableArray alloc]init];
    [self.view addSubview:self.view_table];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.array_data count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.target_type isEqualToString:@"STRATEGY"]){
        return 115;
    }else{
        return 85;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    
    NSArray *nibView = [[NSBundle mainBundle]loadNibNamed:@"SportsCell" owner:self options:nil];
    NSArray *nibView2 = [[NSBundle mainBundle]loadNibNamed:@"CommonCell" owner:self options:nil];
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CollectionCell"];
    if([self.target_type isEqualToString:@"NEWS"]){
        cell = nibView2[0];
        NSDictionary *cellDic = self.array_data[indexPath.row];
        NSString *imgUrl = [Common valueForKey:@"cover" dic:cellDic];
        NSString *title = [Common valueForKey:@"name" dic:cellDic];
        NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
        NSString *source_name = [Common valueForKey:@"source_name" dic:cellDic];
        NSString *comment_cnt = [NSString stringWithFormat:@"%@", [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic]];
        UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
        [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
        [cell addSubview:image];
        UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
        [titleLab setNumberOfLines:2];
        titleLab.text = title;
        [titleLab sizeToFit];
        [cell addSubview:titleLab];
        CGRect frame = titleLab.frame;
        frame.size.width = 216;
        titleLab.frame = frame;
        [self tagSetup:tagsList titleLabHeight:frame.size.height cell:cell];
        UILabel *price = (UILabel*)[cell viewWithTag:1005];
        [price removeFromSuperview];
        UIImageView *districtNameImg = (UIImageView*)[cell viewWithTag:2001];
        [districtNameImg removeFromSuperview];
        UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
        districtNameLab.text = source_name;
        [cell addSubview:districtNameLab];
        UIImageView* goodImg = (UIImageView*)[cell viewWithTag:2003];
        [goodImg removeFromSuperview];
        UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
        CommontLab.text = comment_cnt;
//        [cell addSubview:CommontLab];
    }
    else if([self.target_type isEqualToString:@"STORES"]){
        cell = [nibView2 objectAtIndex:0];
        NSDictionary *cellDic = self.array_data[indexPath.row];
        NSString *imgUrl = [Common valueForKey:@"cover" dic:cellDic];
        NSString *title = [Common valueForKey:P_NAME dic:cellDic];
        NSString *districtName = [Common valueForKey:P_V2_DISTRICT_NAME dic:cellDic];
        NSString *type_name = [Common valueForKey:P_LABEL dic:cellDic];
        NSString *good = [Common valueForKey:P_V2_GOOD dic:cellDic];
        NSString *comment_cnt = [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic];
        NSString *base_price = [Common valueForKey:P_BASE_PRICE dic:cellDic];
        UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
        [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
        //[titleLab setNumberOfLines:2];
        titleLab.text = title;
        //[titleLab sizeToFit];
        //CGRect frame = titleLab.frame;
        //frame.size.width = 216;
        //titleLab.frame = frame;
        [self tagSetup2:cellDic titleLabHeight:-1 cell:cell];
        UILabel *price = (UILabel*)[cell viewWithTag:1005];
        if ([base_price isEqualToString:@""] || [base_price isEqualToString:@"免费"] || base_price == nil){
            [price removeFromSuperview];
        } else {
            NSArray *priceArray = [base_price componentsSeparatedByString:@"元"];
            price.text = [NSString stringWithFormat:@"%@%@",priceArray[0],@"元起"];
        }
        UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
        districtNameLab.text = [NSString stringWithFormat:@"    %@", districtName];
        UILabel* thirdLab = (UILabel*)[cell viewWithTag:2007];
        thirdLab.text = type_name;
        UILabel* goodLab = (UILabel*)[cell viewWithTag:2004];
        goodLab.text = good;
        UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
        CommontLab.text = comment_cnt;
        
    }else if ([self.target_type isEqualToString:@"GOODS"]){
        cell = [nibView objectAtIndex:1];
        NSDictionary *dic_temp = self.array_data[indexPath.row];
        NSString *imgUrl = [Common valueForKey:@"cover" dic:dic_temp];
        UIImageView *img_head = [(UIImageView *)[cell viewWithTag:70010]retain];
        [img_head setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
        UILabel *lb_username = (UILabel *)[cell viewWithTag:70011];
        lb_username.text = [dic_temp objectForKey:@"name"];
        UILabel *lb_price = (UILabel *)[cell viewWithTag:70012];
        int type = [[Common valueForKey:@"type_id" dic:dic_temp] intValue];
        NSString *string_temp = nil;
        int price = [[Common valueForKey:P_PRICE dic:dic_temp] intValue];
        int prePrice = [[Common valueForKey:P_PREFERENTIAL_PRICE dic:dic_temp] intValue];
        if (prePrice >= 0 && prePrice < price) {
            price = prePrice;
        }
        if(type == 10){
            string_temp = [NSString stringWithFormat:@"%d元 / 小时", price];
        }else{
            string_temp = [NSString stringWithFormat:@"%d元", price];
        }
        lb_price.text = string_temp;
        UIButton *btn_gotoBuy = (UIButton *)[cell viewWithTag:70013];
        NSString *payment_mode = [Common valueForKey:P_PAYMENT dic:dic_temp];
        if ([payment_mode isEqualToString:@"0"]) {
            btn_gotoBuy.backgroundColor = [Common colorWithRGB:0xf8b62d];
        } else {
            [btn_gotoBuy setTitle:@"立即预约" forState:UIControlStateNormal];
        }
        if([[Common valueForKey:@"is_sell" dic:dic_temp]isEqualToString:@"0"]){
            btn_gotoBuy.enabled = NO;
            btn_gotoBuy.backgroundColor = [UIColor grayColor];
        }
        [btn_gotoBuy setTag:6000000 + (indexPath.row - 1)];
        [btn_gotoBuy addTarget:self action:@selector(gotoGoods:) forControlEvents:UIControlEventTouchUpInside];
    }else if([self.target_type isEqualToString:@"STRATEGY"]){
        cell = [nibView2 objectAtIndex:1];
//        UILabel *nothing = (UILabel*)[self.tableView viewWithTag:40000];
//        [nothing removeFromSuperview];
        NSDictionary *cellDic = self.array_data[indexPath.row];
        NSString *img = [Common valueForKey:@"cover" dic:cellDic];
        NSString *name = [Common valueForKey:@"name" dic:cellDic];
        UIImageView *imgView = (UIImageView*)[cell viewWithTag:20001];
        [imgView setImageWithURL:[Common getFullDownloadPathByRelativePath:img] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        UIView *nameView = [cell viewWithTag:20002];
        UILabel *nameLab = (UILabel*)[cell viewWithTag:20003];
        nameLab.text = name;
        [nameLab sizeToFit];
        CGRect frame = nameLab.frame;
        frame.size.width = frame.size.width + 10;
        frame.size.height = nameView.frame.size.height;
        frame.origin.y = nameView.frame.origin.y;
        nameView.frame = frame;
        frame.origin.y = nameLab.frame.origin.y;
        nameLab.frame = frame;

    }
    //    if([self.array_data count])
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s || indexPath:%d", __FUNCTION__, indexPath.row);
    NSDictionary *dic_temp = [NSDictionary dictionaryWithDictionary:[self.array_data objectAtIndex:indexPath.row]];
    [self gotoTargetWithType:self.target_type andTargetId:[[Common valueForKey:@"id" dic:dic_temp] intValue] andTargetUrl:[Common valueForKey:@"url" dic:dic_temp]];
}

//标签描绘
- (void)tagSetup:(NSArray*)tagsList titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    if(tagsList.count <= 0)
    {
        return;
    }
    CGFloat tagX = 0.0;
    int count = [tagsList count] > 3 ? 3 : [tagsList count];
    for (int i = 0; i < count; i++) {
        UIView* tagListView = nil;
        if (height < 20.0) {
            tagListView = [cell viewWithTag:1003];
        } else {
            tagListView = [cell viewWithTag:1004];
        }
        NSDictionary *tagDic = tagsList[i];
        NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
        NSString *rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
        if (rgbArray.count > 1) {
            rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
        }
        NSString *name = [Common valueForKey:P_NAME dic:tagDic];
        UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
        tagView.layer.cornerRadius = 3.0;
        unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
        tagView.backgroundColor = [Common colorWithRGB:color];
        UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
        tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
        tagNameLab.textAlignment = UITextAlignmentCenter;
        tagNameLab.textColor = [UIColor whiteColor];
        tagNameLab.text = name;
        [tagNameLab sizeToFit];
        CGRect frame = tagNameLab.frame;
        frame.size.width = MAX(tagNameLab.frame.size.width + 5, 45);
        frame.size.height = 16;
        frame.origin = tagView.frame.origin;
        tagView.frame = frame;
        frame.origin = tagNameLab.frame.origin;
        tagNameLab.frame = frame;
        [tagView addSubview:tagNameLab];
        [tagListView addSubview:tagView];
        tagX += tagView.frame.size.width + 5;
    }
}

- (void)tagSetup2:(NSDictionary*)cellDic titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
    NSString *open_time = [Common valueForKey:P_OPEN_TIME dic:cellDic];
    UIView* tagListView = tagListView = [cell viewWithTag:1003];
    if(tagsList.count <= 0){
        UILabel *openTimeLab = (UILabel*)[cell viewWithTag:2008];
        openTimeLab.text = open_time;
    } else {
        CGFloat tagX = 0.0;
        int count = [tagsList count] > 3 ? 3 : [tagsList count];
        for (int i = 0; i < count; i++) {
            NSDictionary *tagDic = tagsList[i];
            NSString *cover_path = [Common valueForKey:P_COVER_PATH dic:tagDic];
            NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
            if ([cover_path isEqualToString:@""]) {
                NSString *rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
                if (rgbArray.count > 1) {
                    rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
                }
                NSString *name = [Common valueForKey:P_NAME dic:tagDic];
                UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
                tagView.layer.cornerRadius = 3.0;
                unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
                tagView.backgroundColor = [Common colorWithRGB:color];
                UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
                tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
                tagNameLab.textAlignment = UITextAlignmentCenter;
                tagNameLab.textColor = [UIColor whiteColor];
                tagNameLab.text = name;
                [tagNameLab sizeToFit];
                CGRect frame = tagNameLab.frame;
                frame.size.width = MAX(tagNameLab.frame.size.width + 5, 45);
                frame.size.height = 16;
                frame.origin = tagView.frame.origin;
                tagView.frame = frame;
                frame.origin = tagNameLab.frame.origin;
                tagNameLab.frame = frame;
                [tagView addSubview:tagNameLab];
                [tagListView addSubview:tagView];
                tagX += tagView.frame.size.width + 5;
            } else {
                UIImageView *tagsImg = [[UIImageView alloc]initWithFrame:CGRectMake(tagX, 0, 12, 12)];
                [tagsImg setImageWithURL:[Common getFullDownloadPathByRelativePath:cover_path]];
                [tagListView addSubview:tagsImg];
                tagX += 20;
            }
        }
    }
}



- (void)getCommentList{
    [[ProtocolManager shareInstance]getCollectionsWithLoginName:[ProtocolManager shareInstance].loginName andCount:10 beginNo:_currentIndex + 1 andTarget:self andSelector:@selector(getCommentListCallBack:)];
}

- (void)getCommentListWithType{
    [[ProtocolManager shareInstance]getCollectionWithType:self.target_type andLoginname:[ProtocolManager shareInstance].loginName andCount:10 andBeginNo:_currentIndex + 1 andTarget:self andSelector:@selector(getCommentListCallBack:)];
}

- (void)getCommentListCallBack:(NSDictionary *)dic{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic);
    if(dic == nil){
        [self resetPullTableViewState];
        return;
    }
    
    if([[Common valueForKey:@"respCode" dic:dic]isEqualToString:@"000"]){
//        self.array_data = [[NSMutableArray alloc]init];
        NSArray *array_temp = [NSArray arrayWithArray:[Common valueForKey:[TransforController getLowOrHighCaseChangeWithString:self.target_type andIsChangeToHigh:NO] dic:dic]];
        
        for(int i = 0; i < array_temp.count; i++){
            [self.array_data addObject:array_temp[i]];
        }
        [self.view_table reloadData];
        if (array_temp.count < 10 ) {
            [self setEnableLoadMore:NO];
        }
        else {
            [self setEnableLoadMore:YES];
        }
        self.currentIndex += [array_temp count];
    }else{
        self.array_data = [[NSMutableArray alloc]init];
    }
    [[Common shareInstance]stopLoadingView];
    [self resetPullTableViewState];
}

- (void)gotoTargetWithType:(NSString *)type andTargetId:(int)target_id andTargetUrl:(NSString *)target_url{
    if([type isEqualToString:@"STORES"]){
        SportsDetailViewController *storeViewController = [[SportsDetailViewController alloc]init];
        storeViewController.target_id = target_id;
        storeViewController.hidesBottomBarWhenPushed = YES;
        [self.instance_navigation pushViewController:storeViewController animated:YES];
    }else if([type isEqualToString:@"NEWS"]){
//        NSString *url = [NSString stringWithFormat:@"%@%d", target_url, target_id];
        WebIOS *web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrameNoTabBar url:[Common getUrlByString:target_url]];
        //        web.title = [Common valueForKey:P_BRIEFINTRO dic:dic];
        web.target_id = target_id;
        web.type = @"NEWS";
        web.hidesBottomBarWhenPushed = YES;
        [self.instance_navigation pushViewController:web animated:YES];
    }else if([type isEqualToString:@"GOODS"]){
        GoodDetailViewController *goodDetailViewController = [[GoodDetailViewController alloc]init];
        goodDetailViewController.goodId = target_id;
        goodDetailViewController.hidesBottomBarWhenPushed = YES;
        
        [self.instance_navigation pushViewController:goodDetailViewController animated:YES];
    }else if([type isEqualToString:@"STRATEGY"]){
        [self getContent:target_id];
    }
}

- (void)gotoGoods:(id)sender{
    UIButton *btn = (UIButton *)sender;
    int target = btn.tag - 6000000;
    OrderViewController *orderViewCtrl = [[OrderViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    NSDictionary *dic_temp = self.array_data[target];
    orderViewCtrl.storeId = [[Common valueForKey:@"id" dic:dic_temp]intValue];
    orderViewCtrl.goodsInfo = [Common valueForKey:@"name" dic:dic_temp];
    //    orderViewCtrl.storeInfo = self.storeInfo;
    //    NSDictionary *cellData = self.goodDetail;
    orderViewCtrl.product_name = [Common valueForKey:P_NAME dic:dic_temp];
    orderViewCtrl.product_price = [Common valueForKey:P_PRICE dic:dic_temp];
    orderViewCtrl.goodsId = [Common valueForKey:P_ID dic:dic_temp];
    
    [self.instance_navigation pushViewController:orderViewCtrl animated:YES];
}

- (void)getContent:(int)strategyId
{
    [[ProtocolManager shareInstance] getContent:strategyId target:self selector:@selector(getContentCallback:)];
}

#pragma mark - Protocol call back
- (void)getContentCallback:(NSDictionary*)dic
{
    NSLog(@"%s || getContentCallback %@", __FUNCTION__, dic);
    if (dic == nil) {
        
        return;
    }
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if (![respCode isEqualToString:CODE_HANDLE_SUCCESS]) {
        return;
    }
    StrategyDetailViewController *strategyDetailViewCtrl = [[StrategyDetailViewController alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.origin.x, [UIScreen mainScreen].bounds.origin.y, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - HEIGHT_BOTTOM_BAR - HEIGHT_STATUS_BAR)];
    strategyDetailViewCtrl.detailInfo = dic;
    int strategyId = [[Common valueForKey:P_ID dic:dic] intValue];
    for (NSDictionary* dic in self.array_data) {
        int Id = [[Common valueForKey:P_ID dic:dic] intValue];
        if (Id == strategyId) {
            strategyDetailViewCtrl.strategyInfo = dic;
            break;
        }
    }
    [self.instance_navigation pushViewController:strategyDetailViewCtrl animated:YES];
}


- (void)refreshTableView{
    NSLog(@"%s || actions'been actived.", __FUNCTION__);
    [self getCommentList];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = -1;
    self.array_data = [[NSMutableArray alloc]init];
    [self getCommentList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getCommentList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

- (void)setEnableRefresh:(BOOL)flag
{
    ((PullTableView*)self.view_table).enableRefresh = flag;
}

- (void)setEnableLoadMore:(BOOL)flag
{
    ((PullTableView*)self.view_table).enableLoadingMore = flag;
}

- (void)setPullRefreshDate:(NSDate *)date
{
    ((PullTableView*)self.view_table).pullLastRefreshDate = date;
}

- (void)setPullTableIsRefreshing:(BOOL)refreshing
{
    ((PullTableView*)self.view_table).pullTableIsRefreshing = refreshing;
}
- (void)setPullTableIsLoadMore:(BOOL)loadMore
{
    ((PullTableView*)self.view_table).pullTableIsLoadingMore = loadMore;
}

- (void)reloadRowIndexInSection:(int)section row:(int)row
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.view_table reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}

@end
